<template>
  <div id="app">
    <div>
      <span>姓名:</span>
      <input type="text" v-model.trim="uname" />
    </div>
    <div>
      <span>年龄:</span>
      <input type="number" v-model.number="age" />
    </div>
    <div>
      <span>性别:</span>
      <select v-model="sex">
        <option value="男">男</option>
        <option value="女">女</option>
      </select>
    </div>
    <div>
      <button @click="addXg">添加/修改</button>
    </div>
    <div>
      <table border="1" cellpadding="10" cellspacing="0">
        <tr>
          <th>序号</th>
          <th>姓名</th>
          <th>年龄</th>
          <th>性别</th>
          <th>操作</th>
        </tr>
        <tr v-for="(item, index) in arr" :key="item.id">
          <td>{{ index + 1 }}</td>
          <td>{{ item.uname }}</td>
          <td>{{ item.age }}</td>
          <td>{{ item.sex }}</td>
          <td>
            <button @click="remove(index)">删除</button>
            <button @click="edit(index)">编辑</button>
          </td>
        </tr>
      </table>
    </div>
  </div>
</template>
<script>
export default {
  data() {
    return {
      uname: "",
      age: "",
      sex: "",
      arr: [
        { uname: "Tom", age: 25, sex: "男" },
        { uname: "Jone", age: 19, sex: "女" },
        { uname: "小红", age: 14, sex: "女" },
      ],
      selectIndex: "",
      flag: false,
    };
  },
  methods: {
    addXg() {
      if (this.uname === "" || this.age === "") {
        alert("不能输入空");
        return;
      }
      if (!this.flag) {
        this.arr.push({
          id: this.id,
          uname: this.uname,
          age: this.age,
          sex: this.sex,
        });
      } else {
        this.arr.splice(this.selectIndex, 1, {
          id: this.id,
          uname: this.uname,
          age: this.age,
          sex: this.sex,
        });
      }
      (this.uname = ""), (this.age = ""), (this.sex = "");
    },
    edit(i) {
      this.uname = this.arr[i].uname;
      this.age = this.arr[i].age;
      this.sex = this.arr[i].sex;
      this.selectIndex = this.arr.findIndex((item) => item.id === i + 1);
      this.flag = true;
    },
    remove(ind) {
      this.arr.splice(ind, 1);
    },
  },
};
</script>
<style scoped>
button {
  margin-left: 5px;
}
</style>
